//
//  CampusQuestionDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/29.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusQuestionDetailViewController.h"
#import "CampusQuestionReplyListViewController.h"
#import "CampusQuestionDetailHoverView.h"
#import "CampustQuesionDetailHeaderView.h"
#import "CampusQuestionReplyView.h"
#import "CampusQuestionAnswerModel.h"
#import "CampusQuestionDetailModel.h"

@interface CampusQuestionDetailViewController ()<CampusQuestionDetailHoverViewDelegate,CampustQuesionDetailHeaderViewDelegate>
@property (nonatomic,copy)NSArray *answerArray;
@property (nonatomic,strong)CampusQuestionDetailModel *dtlModel;
@property (nonatomic,assign)NSInteger totalCount;
@property (nonatomic,assign)BOOL noMoreData;
@property (nonatomic,strong)CampustQuesionDetailHeaderView *headerView;
@property (nonatomic,strong)CampusQuestionDetailHoverView *hoverView;

@property (nonatomic,strong)NSTimer *timer;

@property (nonatomic,assign)NSInteger timeCount;

@end

@implementation CampusQuestionDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    

    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
  
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;

    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
  
    [self.timer invalidate];
    self.timer = nil;
}

- (JXPagerView *)preferredPagingView {
    return [[JXPagerView alloc] initWithDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setUI];
    
    [self setTime];
    
    [self loadDataSource];
    
}

- (void)setUI{
    self.pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    self.pagerView.isListHorizontalScrollEnabled = YES;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    
    [self.view addSubview:self.pagerView];
    self.pagerView.frame = CGRectMake(0, 0, kScreenW, kScreenH - kNavBarHeight);
}

- (void)back{
    
    if (self.timeCount > 60) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateQuestionTime" object:nil userInfo:@{@"data":self.dtlModel.id}];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 设置时间
- (void)setTime{
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)completionDelayTimerFired{
    self.timeCount++;
}

- (void)loadDataSource{
    
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadQuestionDetail];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadAnswerList];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    
        [self.pagerView reloadData];
    });

}

- (void)loadQuestionDetail{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.questionId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {
           
        self.dtlModel = [CampusQuestionDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadAnswerList{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.questionId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolAnswerList];
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(20);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolAnswerList) parames:param success:^(id responseObj) {
        dispatch_semaphore_signal(sema);
        
        self.answerArray = [CampusQuestionAnswerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
    
        self.totalCount = [responseObj[RESPONSE][TOTAL]intValue];
        
        self.noMoreData = [responseObj[RESPONSE][LASTPAGE]boolValue];
        
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}


#pragma mark - JXPagerMainTableViewGestureDelegate
- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
#pragma mark - JXPagerViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    if (self.dtlModel == nil) {
        return [UIView new];
    }
    self.headerView = [[CampustQuesionDetailHeaderView alloc]init];
    [self.headerView setModel:self.dtlModel];
    self.headerView.delegate = self;
    return self.headerView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return self.dtlModel.itemHeight;
}
- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 66;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    if (self.dtlModel == nil) {
        return [UIView new];
    }
    self.hoverView = [[CampusQuestionDetailHoverView alloc]init];
    [self.hoverView setAnswerCount:self.totalCount];
    self.hoverView.delegate = self;
    return self.hoverView;
}
- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return 1;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"list"] = self.answerArray;
    param[@"status"] = @(self.noMoreData);
    param[@"questionId"] = self.questionId;
    param[@"targetId"] = self.targetAnswerId;
    CampusQuestionReplyListViewController *vc = [[CampusQuestionReplyListViewController alloc]initWithParam:param];
    __weak typeof(self)weakSelf = self;
    vc.update = ^{
        weakSelf.totalCount--;
        [weakSelf.hoverView setAnswerCount:weakSelf.totalCount];
    };
    return vc;
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
    
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark -CampusQuestionDetailHoverViewDelegate
-(void)showReply{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    __weak typeof(self)weakSelf = self;
    CampusQuestionReplyView *replyView = [[CampusQuestionReplyView alloc]initWithCompleteBlock:^(NSString * _Nonnull content) {
        if (content.length != 0) {
            [weakSelf.view endEditing:YES];
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"answerText"] = content;
            param[@"questionId"] = weakSelf.dtlModel.id;
            param[@"schoolId"] = weakSelf.dtlModel.schoolId;
            param[@"userId"] = [RPAppManager getCustomerId];
            param[@"md5"] = [RPAppManager md5StrWithApi:AddSchoolAnswer];
            [SVProgressHUD show];
            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddSchoolAnswer) parames:param success:^(id responseObj) {
                [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"发布成功" duration:2 finishHandler:nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCamputAnswerListSource" object:nil];
               
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateDetailQuestionAnswerCount" object:nil userInfo:@{@"data":weakSelf.dtlModel.id,@"status":@(YES)}];
                weakSelf.totalCount++;
              
                [weakSelf.hoverView setAnswerCount:weakSelf.totalCount];
                
            } failure:^(NSError *error) {
                [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
            }];
        }
    }];
    [replyView show];
}

- (void)showCreateUserInfo{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":self.dtlModel.userVM.id,@"loadType":@(1)} completion:nil];
}

@end
